<template>
  <div class="container" :style="{ backgroundImage: backgroundGradient }">
    <!-- 主容器 -->
    <div class="box" :style="{ backgroundImage: backgroundGradient }">
      <!-- 系统管理盒子 -->
      <div class="box-title">
        <!-- 标题部分 -->
        <h2>系统管理</h2>
        <h5>管理系统的基础配置和用户修改基本信息</h5>
      </div>
      <div class="box-item">
        <!-- 内容部分 -->
        <ul>
          <!-- 操作按钮列表 -->
          <li :style="{ backgroundImage: backgroundGradient }">
            <!-- 操作按钮组 -->
            <el-button
              type="primary"
              icon="el-icon-document-checked"
              class="box-item-button"
              @click="saveSettings"
              >保存设置</el-button
            >
            <el-button
              v-if="isAdmin"
              type="primary"
              icon="el-icon-refresh"
              class="box-item-button"
              @click="resetSettings"
              >重置默认</el-button
            >
            <el-button
              v-if="isAdmin"
              type="primary"
              icon="el-icon-coin"
              class="box-item-button"
              @click="exportData"
              >备份数据</el-button
            >
          </li>

          <!-- 用户基本设置 -->
          <li
            :style="{ backgroundImage: backgroundGradient }"
            v-if="currentUser"
          >
            <h3 class="box-item-title">用户基本设置</h3>

            <!-- 用户头像 -->
            <div class="form-group">
              <span class="box-item-text-left">用户头像:</span>
              <el-upload
                class="avatar-uploader"
                action="#"
                :http-request="customUpload"
                :show-file-list="false"
                :on-change="handleChange"
                :auto-upload="false"
              >
                <img v-if="avatarUrl" :src="avatarUrl" class="avatar-preview" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>  
            </div>

            <!-- 用户名称 -->
            <div class="form-group">
              <span class="box-item-text-left">用户名称:</span>
              <span class="box-item-text-right">
                <el-input
                  v-model="currentUser.username"
                  placeholder="请输入用户名"
                />
              </span>
            </div>

            <!-- 用户密码 -->
            <div class="form-group">
              <span class="box-item-text-left">用户密码:</span>
              <span class="box-item-text-right">
                <el-input
                  type="password"
                  v-model="password"
                  show-password
                  placeholder="请输入新密码"
                />
              </span>
            </div>

            <!-- 用户背景颜色 -->
            <div class="form-group">
              <span class="box-item-text-left">用户背景颜色:</span>
              <span class="box-item-text-right">
                <el-color-picker v-model="currentUser.backgroundColor" />
              </span>
            </div>
          </li>

          <!-- 借阅设置 -->
          <li v-if="isAdmin" :style="{ backgroundImage: backgroundGradient }">
            <h3 class="box-item-title">借阅设置</h3>
            <div class="form-group">
              <span class="box-item-text-left">借书限额:</span>
              <span class="box-item-text-right">
                <el-input-number
                  v-model.number="systemParams.borrowLimit"
                  controls-position="right"
                />
              </span>
            </div>
            <div class="form-group">
              <span class="box-item-text-left">借书期限:</span>
              <span class="box-item-text-right">
                <el-input-number
                  v-model.number="systemParams.borrowPeriod"
                  controls-position="right"
                />
              </span>
            </div>
            <div class="form-group">
              <span class="box-item-text-left">每日逾期罚金:</span>
              <span class="box-item-text-right">
                <el-input-number
                  v-model.number="systemParams.dailyOverdueFine"
                  controls-position="right"
                />
              </span>
            </div>
          </li>

          <!-- 导出Excel和恢复数据库设置 -->
          <li v-if="isAdmin" :style="{ backgroundImage: backgroundGradient }">
            <el-button
              type="primary"
              icon="el-icon-document-checked"
              class="box-item-button"
              @click="exportExcel"
              >导出Excel</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-refresh-right"
              class="box-item-button"
              @click="triggerFileSelect"
              >恢复图书信息</el-button
            >
            <input
              type="file"
              id="sqlFileInput"
              accept=".sql"
              style="display: none"
              @change="restoreThebookInformation"
            />
          </li>
        </ul>
      </div>
    </div>
  </div>

  <!-- 隐藏的文件上传 input -->
</template>

<script>
import userBackgroundColorUtil from "@/util/userBackgroundColor.js";
import userSettingsService from "@/Service/userColorAndUrl.js";
import { getUser, getAvatarURLByUserId } from "@/Service/user-managament.js";
import systemFunctionService from "@/Service/system-function.js";
import { getUserNameAndPassword } from "@/Service/user-nameandpassword.js";
import { putUpdataParameters } from "@/Service/update-parameters.js";
import { userUpdataParameters } from "@/Service/update-parameters2.js";
import { getBookInformation } from "@/Service/book-information";
import { getBookSql } from "@/Service/book-sql";
import { uploadSQLFile } from "@/Service/book-update"; // 引入封装好的方法
// import { loginUtil } from "../Service/login.js";
import { getUserId } from "@/Service/huo-qu.js";

export default {
  data() {
    return {
      currentUser: null,
      isAdmin: false,
      currentUserId: null, // 初始化为 null
      avatarUrl: "",
      userBackgroundColor: userBackgroundColorUtil.getDefaultBackgroundColor(),
      backgroundGradient: userBackgroundColorUtil.getDefaultGradient(),
      username: "",
      password: "",
      userAvatar: "",
      userAvatarFile: null,
      systemParams: {
        borrowLimit: 0,
        borrowPeriod: 0,
        dailyOverdueFine: 0,
      },
    };
  },
  created() {
    const userId = getUserId(); // 同步获取
    this.currentUserId = userId ? parseInt(userId) : 1;
  },
  watch: {
    userBackgroundColor(newColor) {
      this.backgroundGradient = userBackgroundColorUtil.getGradient(newColor);
      if (this.currentUser) {
        this.currentUser.backgroundColor = newColor;
      }
    },
    "currentUser.backgroundColor"(newColor) {
      if (newColor) {
        this.userBackgroundColor = newColor;
        this.backgroundGradient = userBackgroundColorUtil.getGradient(newColor);
      }
    },
  },
  async mounted() {
    await this.fetchUserAndCheckAdmin(); // 确保在其他操作前获取用户信息
    const params = await systemFunctionService.getSystemFunciton();
    if (params) {
      this.systemParams = params;
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isValidType = file.type.startsWith("image/");
      if (!isValidType) {
        this.$message.error("只能上传图片文件！");
      }
      return isValidType;
    },

    handleAvatarSuccess(response, file) {
      // 使用本地预览 URL 显示图片
      this.avatarUrl = URL.createObjectURL(file);
      this.userAvatarFile = file; // 保存文件对象供后续提交使用
    },
    handleChange(file) {
      this.userAvatarFile = file.raw; // 保存原始 File 对象
      this.avatarUrl = URL.createObjectURL(file.raw); // 预览
    },
    customUpload() {
      // 拦截上传行为，由 saveSettings 控制统一提交
      return false;
    },
    async fetchUserAndCheckAdmin() {
      try {
        const response = await getUser(this.currentUserId);

        // 1. 修正成功判断（从 response 直接取数据）
        if (response) {
          this.userData = response;
          this.userProfile = response.profile || {};
          this.currentUser = {
            ...this.userData,
            backgroundColor: this.userProfile.backgroundColor,
          };
          console.log(this.currentUser);
          this.isAdmin = response.isAdmin;
          this.avatarUrl = await getAvatarURLByUserId(this.currentUserId);
          console.log("avatar:" + this.avatarUrl);
          console.log("头像完整路径eeee:", this.currentUser.avatarUrl);
          // 2. 正确生成完整头像URL（注意添加斜杠）
          const fullAvatarUrl = `${window.location.origin}/user/${this.currentUserId}/avatar`;
          console.log("最终头像完整路径:", fullAvatarUrl);
          // console.log(
          //   "%c点击访问头像",
          //   "color:blue;cursor:pointer",
          //   fullAvatarUrl
          // );
        } else {
          console.error("接口返回异常:", response.data?.message || response);
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    },

    async saveSettings() {
      let shouldSavePassword = true;
      let shouldSaveSettings = true;

      // 检查密码是否为空
      if (!this.password || !this.currentUser.userAvatar) {
        this.$message.error("当前密码或用户名为空，不执行更改密码操作。");
        shouldSavePassword = false;
      }

      // 检查背景颜色和头像 URL 是否为空
      if (!this.currentUser.backgroundColor || !this.avatarUrl) {
        this.$message.error("当前头像或背景色未改变，不执行更改操作。");
        shouldSaveSettings = false;
      }

      // 如果密码和用户头像不为空，则执行更改密码的操作
      if (shouldSavePassword) {
        try {
          await getUserNameAndPassword.call(this);
          this.$message.success("用户名/密码保存成功");
        } catch (error) {
          console.error("用户名/密码保存失败:", error);
          alert("用户名或密码保存失败");
        }
      }

      // 如果背景颜色和头像 URL 不为空，则执行更改头像和背景色的操作
      if (shouldSaveSettings) {
        try {
          await userSettingsService.saveSettings.call(this);
          this.$message.success("头像/背景保存成功");
        } catch (error) {
          this.$message.error("头像或背景色保存失败");
        }
      }

      // ✅ 只有管理员才能保存系统参数
      if (this.isAdmin) {
        try {
          await putUpdataParameters.call(this);
          this.$message.success("系统参数保存成功");
        } catch (error) {
          console.error("系统参数保存失败:", error);
          alert("系统参数保存失败");
        }
      }
    },

    async resetSettings() {
      try {
        const res = await userUpdataParameters.call(this);
        this.$message.success("重置默认参数保存成功");
        console.log("重置默认后的参数:", res.data);
      } catch (error) {
        console.error("头像/背景色保存失败:", error);
        alert("头像或背景色保存失败");
      }
    },

    async exportData() {
      try {
        await getBookSql.call(this);
      } catch (error) {
        console.error("sql文件导出失败:", error);
        alert("sql文件导出失败");
      }
    },

    async exportExcel() {
      try {
        await getBookInformation.call(this);
      } catch (error) {
        console.error("excel导出失败:", error);
        alert("excel导出失败");
      }
    },

    // 触发隐藏的文件选择框
    triggerFileSelect() {
      document.getElementById("sqlFileInput").click();
    },

    // 处理 SQL 文件上传
    async restoreThebookInformation() {
      const fileInput = document.getElementById("sqlFileInput");
      const file = fileInput.files[0];

      if (!file) {
        alert("请选择一个 SQL 文件");
        return;
      }

      try {
        const result = await uploadSQLFile(file); // 使用封装好的方法上传
        alert(result.data.message || "SQL 文件上传成功");
      } catch (err) {
        alert("上传失败：" + err.message);
      }

      // 清空 input 的值，允许重复上传同一个文件
      fileInput.value = null;
    },

    // 上传头像
    uploadAvatar(event) {
      const file = event.target.files[0];
      if (!file || !file.type.startsWith("image/")) {
        alert("请选择有效的图片文件");
        return;
      }

      this.userAvatarFile = file;
      const avatarPreview = URL.createObjectURL(file);
      this.currentUser.avatarUrl = avatarPreview;
    },
  },
};
</script>

<style scoped>
/* 全局样式 */
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: "华文楷体", sans-serif;
  background-color: #f4f6f8;
  color: #333;
}

/* 主容器样式 */
.container {
  height: 100%;
  width: 800px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: linear-gradient(135deg, #e0eafc, #cfdef3);
  padding-top: 20px;
  margin-left: 230px;
}

/* 系统管理盒子样式 */
.box {
  width: 100%;
  max-width: 980px;
  min-height: 600px;
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease-in-out;
  margin: 0 auto;
  margin-top: 40px;
}

/* 标题部分样式 */
.box-title {
  color: #333;
  margin-bottom: 20px;
}

.box-title h2 {
  font-size: 26px;
  font-weight: bold;
  margin: 0;
}

.box-title h5 {
  font-size: 14px;
  margin-top: 5px;
  color: #666;
}

/* 内容部分样式 */
.box-item ul {
  list-style-type: none;
  padding: 0;
}

.box-item ul li {
  background-color: #f9f9f9;
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.box-item ul li:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 表单项布局 */
.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

/* 左侧标签样式 */
.box-item-text-left {
  flex: 1;
  font-size: 14px;
  color: #555;
  font-weight: 500;
  margin-right: 10px;
}

/* 右侧输入区域 */
.box-item-text-right {
  flex: 2;
  display: flex;
  justify-content: flex-end;
}

/* El-UI 输入组件统一样式 */
.el-input,
.el-input-number,
.el-color-picker {
  width: 100%;
  max-width: 240px;
}

/* 缩小输入框高度与内边距 */
.el-input ::v-deep .el-input__inner,
.el-input-number ::v-deep .el-input__inner {
  height: 34px;
  line-height: 34px;
  font-size: 13px;
  padding: 0 10px;
  border-radius: 6px;
  border: 1px solid #ddd;
  transition: border-color 0.3s ease;
}

/* 聚焦高亮 */
.el-input ::v-deep .el-input__inner:focus,
.el-input-number ::v-deep .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 颜色选择器也缩放 */
.el-color-picker ::v-deep .el-color-picker__trigger {
  height: 34px;
  width: 100%;
  max-width: 240px;
  border-radius: 6px;
  border: 1px solid #ddd;
  font-size: 13px;
  padding: 0 10px;
}

/* 文件上传 input 缩小 */
input[type="file"] {
  height: 34px;
  padding: 0 10px;
  font-size: 13px;
  border-radius: 6px;
  border: 1px solid #ddd;
  background: #f9f9f9;
  width: 100%;
  max-width: 240px;
  box-sizing: border-box;
}

/* 头像预览图 */
.avatar-preview {
  width: 60px;
  height: 60px;
  margin-top: 10px;
  border-radius: 8px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
}

/* 按钮样式 */
.box-item-button {
  margin: 0 10px;
  border-radius: 25px;
  font-size: 14px;
  padding: 10px 20px;
  transition: all 0.3s ease;
  background-color: #409eff;
  border: none;
  color: white;
  cursor: pointer;
}

.box-item-button:hover {
  background-color: #337ecc;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

/* 响应式适配 */
@media (max-width: 1024px) {
  .box {
    width: 90%;
    margin: 0 auto;
  }

  .box-item-text-left,
  .box-item-text-right {
    font-size: 14px;
  }

  .form-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .box-item-text-left {
    margin-bottom: 8px;
  }

  .box-item-text-right {
    width: 100%;
    justify-content: flex-start;
  }

  .el-input,
  .el-input-number,
  .el-color-picker,
  input[type="file"] {
    max-width: 100%;
  }
}
</style>